using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace net.notdot.Attercop.Client
{
    [Serializable]
    public struct HashCacheEntry
    {
        public DateTime LastModified;
        public byte[] Hash;
    }

    [Serializable]
    public class HashCache : Dictionary<string, HashCacheEntry>
    {
        private const string datafile = "hashcache.dat";

        public void Add(byte[] key, HashCacheEntry value)
        {
            this.Add(Convert.ToBase64String(key), value);
        }

        protected HashCache() : base() { }

        protected HashCache(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);
        }

        public static void Load()
        {
            if (File.Exists(datafile))
            {
                FileStream s = new FileStream(datafile, FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryFormatter formatter = new BinaryFormatter();
                m_Instance = (HashCache) formatter.Deserialize(s);
                s.Close();
            }
            else
            {
                m_Instance = new HashCache();
            }
        }

        public static void Save()
        {
            FileStream s = new FileStream(datafile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(s, m_Instance);
            s.Close();
        }

        private static HashCache m_Instance = null;
        public static HashCache Instance
        {
            get
            {
                if (m_Instance == null)
                    Load();
                return m_Instance;
            }
        }
    }
}
